package xin.yogee.ms.utils.io;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author JackieQ
 * @since 2019/4/10
 */
public class UploadUtil {

    public static List<String> fileUpload(MultipartHttpServletRequest multiRequest,String savePath) {
        List<MultipartFile> list = multiRequest.getFiles("file");
        List<String> imgList = new ArrayList<>();
        for (MultipartFile file : list){
            if (file != null){
                String fileName = file.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                String name = IdUtil.fastUUID() + suffix;
                String path = "/upload/" + DateUtil.thisYear() + "/" + String.valueOf(Integer.valueOf(DateUtil.thisMonth()) + 1) + "/";
                //验证文件夹是否存在
                if (!FileUtil.isDirectory(savePath + path)){
                    FileUtil.mkdir(savePath + path);
                }
                File localFile = new File(savePath + path + name);
                try {
                    file.transferTo(localFile);
                }catch (IOException e){
                    System.out.println("文件上传错误，错误信息:" + e);
                    return imgList;
                }
                imgList.add(path + name);
            }
        }
        return imgList;
    }

}
